import Vue from "vue";
import Router from "vue-router";

Vue.use(Router);

const router = new Router({
  mode: "history",
  routes: [
    {
      path: "/main",
      name: "main",
      component: () => import("@/views/Main.vue"),
      children: [
        {
          path: "/main",
          redirect: "/dashboard",
        },
        {
          path: "/dashboard",
          name: "Dashboard",
          component: () => import("@/views/Dashboard.vue"),
          meta: { titleText: "首页" },
        },
        {
          path: "/products",
          name: "Products",
          component: () => import("@/views/Products.vue"),
          meta: { titleText: "商品列表" },
        },
        {
          path: "/products/goodsDetail/:objectId?",
          name: "goodsDetail",
          component: () => import("@/views/goodsDetail.vue"),
          meta: { titleText: "商品详情" },
        },
        {
          path: "/orders",
          name: "Orders",
          component: () => import("@/views/Orders.vue"),
          meta: { titleText: "订单列表" },
        },
        {
          path: "/orders/orderDetail",
          name: "orderDetail",
          component: () => import("@/views/orderDetail.vue"),
          meta: { titleText: "订单详情" },
        },
        {
          path: "/customers",
          name: "Customers",
          component: () => import("@/views/Customers.vue"),
          meta: { titleText: "用户列表" },
        },
        {
          path: "/maparea",
          name: "maparea",
          component: () => import("@/views/Maparea.vue"),
          meta: { titleText: "配送范围" },
        },
        {
          path: "*",
          component: () => import("@/views/NotFound.vue"),
        },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/Login.vue"),
    },
    {
      path: "/",
      redirect: "main",
    },
  ],
});

// 路由守卫，判断用户是否登录
router.beforeEach((to, from, next) => {
  const isLogin = JSON.parse(localStorage.getItem("userInfo") || "{}")
    ?.sessionToken
    ? true
    : false;
  // console.log("token====", localStorage.getItem("userInfo"), isLogin);
  if (isLogin && to.path !== "/login") {
    // 有token 但不是去 login页面 通过
    next();
  } else if (isLogin && to.path === "/login") {
    // 有token 但是去 login页面 不通过 重定向到首页
    next("/");
  } else if (!isLogin && to.path !== "/login") {
    // 没有token 但不是去 login页面 不通过（未登录不给进入）
    next("/login");
  } else {
    // 剩下最后一种 没有token 但是去 login页面 通过
    next();
  }
});

export default router;
